package com.simtek.simplayer;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.DownloadListener;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.simtek.simplayer.R.id;
import com.simtek.simplayer.R.string;
import com.simtek.simplayer.utils.PlayerLinkUtils;

public class MainActivity extends FragmentActivity implements OnClickListener {
	private WebView				webView;

	private View				tabMovie;
	private View				tabNews;

	public static final String	MOVIE_SITE_URL	= "http://bum.vn/html/clip/home";
//	public static final String	MOVIE_SITE_URL	= "http://local.bum.vn/html/clip/home";
	public static final String	NEWS_SITE_URL	= "http://bum.vn/app/rss/";

	@SuppressLint({
			"JavascriptInterface", "SetJavaScriptEnabled"
	})
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main_layout);
		String deviceId = Settings.Secure.getString(getContentResolver(),
				Settings.Secure.ANDROID_ID);

		tabMovie = findViewById(id.actionTabMovie);
		tabNews = findViewById(id.actionTabNews);

		tabMovie.setSelected(true);

		tabMovie.setOnClickListener(this);
		tabNews.setOnClickListener(this);

		if (webView == null) {
			webView = (WebView) findViewById(R.id.activity_main_web_content);
			WebSettings settings = webView.getSettings();
			settings.setJavaScriptEnabled(true);
			settings.setDomStorageEnabled(true);
			settings.setNeedInitialFocus(true);
			webView.requestFocus();
			webView.setScrollbarFadingEnabled(true);
			webView.getSettings().setLoadsImagesAutomatically(true);

			webView.addJavascriptInterface(new WebAppInterfaceImp(this, webView), "BUMAPK");

			webView.setWebViewClient(new MyWebViewClient(deviceId));
			webView.setWebChromeClient(new MyWebChromeClient());

			webView.setDownloadListener(new DownloadListener() {
				@Override
				public void onDownloadStart(String url, String userAgent,
						String contentDisposition, String mimetype,
						long contentLength) {
					Intent i = new Intent(Intent.ACTION_VIEW);
					i.setData(Uri.parse(url));
					startActivity(i);
				}
			});

			webView.setBackgroundColor(Color.WHITE);
			webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
		}

		if (savedInstanceState == null) {
			webView.clearHistory();
			webView.loadUrl(PlayerLinkUtils.resolvePath(MOVIE_SITE_URL, deviceId));
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		webView.saveState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		webView.restoreState(savedInstanceState);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu m) {
		new MenuInflater(this).inflate(R.menu.main, m);
		return super.onCreateOptionsMenu(m);
	}

	private long	mBackPressed;

	@Override
	public void onBackPressed() {
		if (webView.canGoBack()) {
			webView.goBack();
		} else {
			if (mBackPressed + 2000L > System.currentTimeMillis()) {
				super.onBackPressed();
				return;
			}
			mBackPressed = System.currentTimeMillis();
			Toast.makeText(this, string.message_press_back_again_to_close,
					Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case R.id.mn_reload:
				webView.reload();
				break;
		}
		return super.onOptionsItemSelected(item);
	}

	boolean	clearHistory	= false;

	private class MyWebViewClient extends WebViewClient {
		String	deviceId;

		public MyWebViewClient(String cid) {
			this.deviceId = cid;
		}

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			if (Uri.parse(url).getHost().endsWith("bum.vn")) {
				url = PlayerLinkUtils.resolvePath(url, deviceId);
				view.loadUrl(url);
				return true;
			}

			return false;
		}

		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			Toast.makeText(activity, "Oh no! " + description,
					Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			if (clearHistory) {
				clearHistory = false;
				webView.clearHistory();
			}
			super.onPageFinished(view, url);
		}
	}

	final Activity	activity	= this;

	private class MyWebChromeClient extends WebChromeClient {
		@Override
		public boolean onJsAlert(WebView view, String url, String message,
				final JsResult result) {
			String title = "Thông báo";
			int idx = message.indexOf("\n");
			if (idx > 0) {
				title = message.substring(0, idx);
				message = message.substring(idx + 1);
			}

			new AlertDialog.Builder(view.getContext())
					.setIcon(android.R.drawable.ic_dialog_alert)
					.setTitle(title)
					.setMessage(message)
					.setPositiveButton(android.R.string.ok,
							new AlertDialog.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									result.confirm();
								}
							}).setCancelable(false).create().show();

			return true;
		}
	}

	@Override
	public void onClick(View v) {
		if (v.isSelected() && webView.getScrollY() != 0) {
			webView.pageUp(true);
		} else {
			if (!v.isSelected()) {
				v.setSelected(true);
				switch (v.getId()) {
					case id.actionTabMovie:
						tabNews.setSelected(false);
						break;
					case id.actionTabNews:
						tabMovie.setSelected(false);
						break;
				}
			}

			String url = "0".equals(v.getTag()) ? MOVIE_SITE_URL : NEWS_SITE_URL;
			webView.loadUrl(PlayerLinkUtils.resolvePath(url,
					Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID)));
			
			// clear ngay history cũ
			webView.clearHistory();
			// đánh dấu sẽ clear history (là link cũ) sau khi load xong link mới này
			clearHistory = true;
		}

//		switch (v.getId()) {
//			case id.actionTabMovie:
//				if (v.isSelected() && webView.getScrollY() != 0) {
//					scrollToTop();
//				} else {
//					v.setSelected(true);
//					tabNews.setSelected(false);
//
//					tabNews.setTag(webView.getUrl());
//					Object tag = tabMovie.getTag();
//					if (tag != null && ((String) tag).startsWith(MOVIE_SITE_URL)) {
//						webView.loadUrl((String) tag);
//						tabMovie.setTag(null);
//					} else {
//						webView.loadUrl(MOVIE_SITE_URL);
//					}
//				}
//				break;
//			case id.actionTabNews:
//				if (v.isSelected() && webView.getScrollY() != 0) {
//					scrollToTop();
//				} else {
//					v.setSelected(true);
//					tabMovie.setSelected(false);
//					tabMovie.setTag(webView.getUrl());
//					Object tag = tabMovie.getTag();
//					if (tag != null && ((String) tag).startsWith(NEWS_SITE_URL)) {
//						webView.loadUrl((String) tag);
//						tabNews.setTag(null);
//					} else {
//						webView.loadUrl(NEWS_SITE_URL);
//					}
//				}
//				break;
//		}
	}

//	private void scrollToTop() {
//		Animator scroll = ObjectAnimator.ofInt(webView, "scrollY", 0);
//		scroll.setInterpolator(new DecelerateInterpolator());
//		scroll.setDuration(500);
//		AnimatorSet set = new AnimatorSet();
//
//		set.play(scroll);
//		set.start();
//	}
}
